package com.whmnx.chitchat.adapter.holder;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMVideo;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.component.photoview.PhotoViewActivity;
import com.tencent.qcloud.tim.uikit.component.video.VideoViewActivity;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.bean.ChatDetailsBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.constants.MessageInfo;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.ui.chat.ChatActivity;
import com.whmnx.chitchat.utils.ImageUtil;
import com.whmnx.chitchat.utils.UItils;
import com.whmnx.chitchat.view.ShowImagesDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * @author Administrator
 */
public class MessageImageHolder2 extends MessageContentHolder2 {

    private static final int DEFAULT_MAX_SIZE = 340;
    private static final int DEFAULT_RADIUS = 10;
    private final List<String> downloadEles = new ArrayList<>();
    private ImageView contentImage;
    private ImageView videoPlayBtn;
    private TextView videoDurationText;
    private boolean mClicking;
    private String imageInfoArray;
    int pos = 0;

    public MessageImageHolder2(View itemView) {
        super(itemView);
    }

    @Override
    public int getVariableLayout() {
        return R.layout.message_adapter_content_image;
    }

    @Override
    public void initVariableViews() {
        contentImage = rootView.findViewById(R.id.content_image_iv);
        videoPlayBtn = rootView.findViewById(R.id.video_play_btn);
        videoDurationText = rootView.findViewById(R.id.video_duration_tv);
    }

    @Override
    public void layoutVariableViews(ChatDetailsBean msg, int position) {
        // msgContentFrame.getBackground().setAlpha(100);
        msgContentFrame.setBackground(null);
        //  msgContentFrame.setBackgroundColor(UItils.getContext().getResources().getColor(R.color.white));
        performImage(msg, position);
       /* switch (msg.getMsgType()) {
          //  case MessageInfo.MSG_TYPE_CUSTOM_FACE:
          //  case MessageInfo.MSG_TYPE_CUSTOM_FACE + 1:
              //  performCustomFace(msg, position);
            //    break;
           // case MessageInfo.MSG_TYPE_IMAGE:
            case MessageInfo.MSG_TYPE_IMAGE + 1:
              //  performImage(msg, position);
                break;
          //  case MessageInfo.MSG_TYPE_VIDEO:
         //   case MessageInfo.MSG_TYPE_VIDEO + 1:
              //  performVideo(msg, position);
              //  break;
            default:
        }*/
    }

    private void performCustomFace(final ChatDetailsBean msg, final int position) {

    }

    private ViewGroup.LayoutParams getImageParams(ViewGroup.LayoutParams params, final ChatDetailsBean msg) {
        params.width = DEFAULT_MAX_SIZE;
        params.height = 340;

        //获取图片真正的宽高
      /*  Glide.with(UItils.getContext())
                .asBitmap()
                .load(imageInfoArray)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int width = resource.getWidth();
                        int height = resource.getHeight();
                        if (width > height) {
                            params.width = DEFAULT_MAX_SIZE;
                            params.height = DEFAULT_MAX_SIZE * width / height;
                        } else {
                            params.width = DEFAULT_MAX_SIZE * width / height;
                            params.height = DEFAULT_MAX_SIZE;
                        }
                    }
                });*/
        return params;
    }

    private void resetParentLayout() {
        ((FrameLayout) contentImage.getParent().getParent()).setPadding(17, 0, 13, 0);
    }

    private void performImage(final ChatDetailsBean msg, final int position) {
        if (null != msg) {
            imageInfoArray = msg.getChatRecord_Content();
        }

       contentImage.setLayoutParams(getImageParams(contentImage.getLayoutParams(), msg));
        // contentImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
        resetParentLayout();
        videoPlayBtn.setVisibility(View.GONE);
        videoDurationText.setVisibility(View.GONE);
        ImageUtil.setImage(contentImage, imageInfoArray);
        //  contentImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
       /* if (null != msg && msg.getMsgBody().size() > 0){
            List<ChatDetailsBean.MsgBodyBean.ImageInfoArrayBean> imageInfoArray = msg.getMsgBody().get(0).getMsgContent().getImageInfoArray();
            if (null != imageInfoArray && imageInfoArray.size() > 0)
        }*/

        List<String> beanList = new ArrayList<>();
        beanList.add(imageInfoArray);
        List<String> imgList = Constants.IMGLIST;
        List<String> imgList2 = Constants.IMGLIST2;
        if (!imgList2.contains(imageInfoArray)){
            imgList2.add(imageInfoArray);
        }

        if (imgList2.size() > 0 && !imgList.contains(imgList2)) {
            imgList.addAll(imgList2);
        }else {
            imgList.addAll(beanList);
        }

        //去重
        List<String> myList = UItils.delRepeat(imgList);
        for (int i = 0; i < myList.size(); i++) {
            if (myList.get(i).contains(imageInfoArray)) {
                pos = i;
                break;
            }
        }


        contentImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              /*  for (int i = 0; i < imgs.size(); i++) {
                    TIMImage img = imgs.get(i);
                    if (img.getType() == TIMImageType.Original) {
                        PhotoViewActivity.mCurrentOriginalImage = img;
                        break;
                    }
                }*/
                MessageEvent messageEvent2 = new MessageEvent();
                messageEvent2.setMessageKey(EventConstants.IMG);
                messageEvent2.setMessageKey2(myList);
                messageEvent2.setMessageKey3(pos);
                EventBus.getDefault().post(messageEvent2);
              //  ShowImagesDialog showImagesDialog = new ShowImagesDialog(ChatActivity.getForegroundActivity(), myList, pos);
              //  showImagesDialog.show();

                //    Intent intent = new Intent(UItils.getContext(), PhotoViewActivity.class);
                //  intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                // intent.putExtra(TUIKitConstants.IMAGE_DATA, imageInfoArray);
                //   intent.putExtra(TUIKitConstants.SELF_MESSAGE, true);
                //  UItils.getContext().startActivity(intent);
            }
        });
        contentImage.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (onItemClickListener != null) {
                    onItemClickListener.onMessageLongClick(view, position, msg);
                }
                return true;
            }
        });
    }

    private void performVideo(final ChatDetailsBean msg, final int position) {
        contentImage.setLayoutParams(getImageParams(contentImage.getLayoutParams(), msg));
        resetParentLayout();
    }

    private void getVideo(TIMVideo video, String videoPath, final MessageInfo msg, final boolean autoPlay, final int position) {
        video.getVideo(videoPath, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                ToastUtil.toastLongMessage("下载视频失败:" + code + "=" + desc);
                msg.setStatus(MessageInfo.MSG_STATUS_DOWNLOADED);
                sendingProgress.setVisibility(View.GONE);
                statusImage.setVisibility(View.VISIBLE);
                mAdapter.notifyItemChanged(position);
                mClicking = false;
            }

            @Override
            public void onSuccess() {
                mAdapter.notifyItemChanged(position);
                if (autoPlay) {
                    play(msg);
                }
                // 有可能播放的Activity还没有显示，这里延迟200ms，拦截压力测试的快速点击
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mClicking = false;
                    }
                }, 200);
            }
        });
    }

    private void play(final MessageInfo msg) {
        statusImage.setVisibility(View.GONE);
        sendingProgress.setVisibility(View.GONE);
        Intent intent = new Intent(TUIKit.getAppContext(), VideoViewActivity.class);
        intent.putExtra(TUIKitConstants.CAMERA_IMAGE_PATH, msg.getDataPath());
        intent.putExtra(TUIKitConstants.CAMERA_VIDEO_PATH, msg.getDataUri());
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        TUIKit.getAppContext().startActivity(intent);
    }
}
